package com.baitengsoft.patentapimonitor.api.service.impl;


import com.baitengsoft.patentapimonitor.api.dao.WebUserDao;
import com.baitengsoft.patentapimonitor.api.entity.*;
import com.baitengsoft.patentapimonitor.api.model.*;
import com.baitengsoft.patentapimonitor.api.model.dto.WebDto;
import com.baitengsoft.patentapimonitor.api.model.dto.WebUserUpdateLoginInfo;
import com.baitengsoft.patentapimonitor.api.model.param.EditUserInfoParam;
import com.baitengsoft.patentapimonitor.api.model.param.MenuOfUserParam;
import com.baitengsoft.patentapimonitor.api.model.param.UserInfoParam;
import com.baitengsoft.patentapimonitor.api.service.*;
import com.baitengsoft.patentapimonitor.common.utils.EncryptionStrategy;
import com.baitengsoft.patentapimonitor.common.utils.PageResult;
import com.baitengsoft.patentapimonitor.common.utils.Res;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 系统用户
 *
 * @author KennyGu
 */
@Service
public class WebUserServiceImpl extends BaseServiceImpl<WebUserinfoEntity> implements WebUserService {

    @Autowired
    org.dozer.Mapper mapper;
    @Autowired
    private WebUserDao webUserDao;
    @Autowired
    private WebPlatformService webPlatformService;
    @Autowired
    private WebUserareaService webUserareaService;
    @Autowired
    private WebPlatformareaService web_platformareaService;
    @Autowired
    private WebUserMenuService webUserMenuService;
    @Autowired
    private WebRolesmenuRlatService webRolesmenuRlatService;
    @Autowired
    private WebMenuService webMenuService;


    @Override
    public WebUserinfoEntity queryByUserName(String username) {
        return webUserDao.queryByUserName(username);
    }

    @Override
    public WebUserinfoEntity queryObject(Long userId) {
        return webUserDao.queryObject(userId);
        //return null;
    }

    @Override
    public PageResult<WebUserInfoModel> searchUserInfos(UserInfoParam param) {

        PageHelper pageHelper = new PageHelper();
        pageHelper.startPage(param.getPage(), param.getPageSize());
        Mapper mapperTk = getMapper();
        Example example = new Example(WebUserinfoEntity.class);
        example.setOrderByClause("createdate DESC");
        Example.Criteria criteria = example.createCriteria();
        criteria.andNotEqualTo("status", -1);
        if (StringUtils.isNotBlank(param.getPlatformID())) {
            criteria.andEqualTo("platformid", param.getPlatformID());
        }
        if (StringUtils.isNotBlank(param.getRolesID())) {
            criteria.andEqualTo("rolesid", param.getPlatformID());
        }
        if (StringUtils.isNotBlank(param.getStatus())) {
            criteria.andEqualTo("status", param.getStatus());
        }
        if (StringUtils.isNotBlank(param.getUserName())) {
            criteria.andLike("name", "%" + param.getUserName().trim() + "%");
        }

        List<WebUserinfoEntity> entities = mapperTk.selectByExample(example);
        PageInfo<WebUserinfoEntity> pageInfo = new PageInfo<>(entities);
        if (entities != null && entities.size() > 0) {

            List<WebUserInfoModel> models = new ArrayList<>();
            for (WebUserinfoEntity entity : entities) {
                WebUserInfoModel model = new WebUserInfoModel();
                mapper.map(entity, model);
                if (entity.getPlatformid() != null && entity.getPlatformid() > 0) {//平台名称
                    WebPlatformEntity webPlatformEntity = webPlatformService.searchById(entity.getPlatformid());
                    if (webPlatformEntity != null) {
                        model.setPlatformName(webPlatformEntity.getName());
                    }
                }
                List<WebUserareaEntity> webUserareaEntities = webUserareaService.searchUserareaByUserId(entity.getId());
                String dataRangeStr = "";//数据范围
                if (webUserareaEntities != null && webUserareaEntities.size() > 0) {
                    for (int i = 0; i < webUserareaEntities.size(); i++) {
                        //if(i>2) break;//只获取前3个区域
                        WebPlatformareaEntity webPlatformareaEntity = web_platformareaService.selectAreaById(webUserareaEntities.get(i).getAreaid());
                        if (webPlatformareaEntity != null) {
                            dataRangeStr += webPlatformareaEntity.getName() + "、";
                        }
                    }
                }
                if (StringUtils.isNotBlank(dataRangeStr)) {
                    model.setDataRangeStr(dataRangeStr.substring(0, dataRangeStr.length() - 1));
                } else {
                    model.setDataRangeStr(dataRangeStr);
                }

                models.add(model);
            }
            ;
            return new PageResult<WebUserInfoModel>(models, param.getPage(), param.getPageSize(), (int) pageInfo.getTotal());
        }
        return null;
    }

    @Override
    @Transactional
    public Integer editUserInfo(EditUserInfoParam param, int userId) {
        WebUserinfoEntity entity = new WebUserinfoEntity();
        mapper.map(param, entity);
        entity.setUpdatedate(new Date());
        entity.setUpdateoperid(userId);
        if (param.getId() > 0) {//编辑
            //加密用户密码
            entity.setPwd(EncryptionStrategy.encrypt(entity.getPwd()));
            Integer udSuccessId = updateByNotNull(entity);
            if (udSuccessId == 0) return 0;//编辑用户表失败
        } else {//新增
            entity.setLogincount(0);
            entity.setCreatedate(new Date());
            entity.setCreateoperid(userId);
            //加密用户密码
            entity.setPwd(EncryptionStrategy.encrypt(entity.getPwd()));
            Integer saveUfSuccessID = saveByNotNull(entity);
            if (saveUfSuccessID == 0) return 0;//新增用户表失败
        }
        //更新栏目关联表
        if (param.getMenuparam() != null && param.getMenuparam().size() > 0) {
            //String[] rolesIds=param.getRolesIds().split(",");
            List<MenuOfUserParam> menuOfUserParams = param.getMenuparam();
            if (param.getId() > 0) {//只有编辑时才会执行删除
                List<WebUsermenuEntity> webUsermenuEntities = webUserMenuService.searchByUserId(param.getId());
                if (webUsermenuEntities != null && webUsermenuEntities.size() > 0) {
                    Integer delSuccessId = webUserMenuService.delUsermenuByUserId(param.getId());
                    if (delSuccessId == 0) {
                        return 0;//删除栏目关联表失败
                    }
                }
            }
            for (MenuOfUserParam menuOfUserParam : menuOfUserParams) {
                WebUsermenuEntity webUsermenuEntity = new WebUsermenuEntity();
                webUsermenuEntity.setUserid(entity.getId());
                webUsermenuEntity.setIsreadonly(menuOfUserParam.getIsReadOnly());
                webUsermenuEntity.setMenuid(menuOfUserParam.getMenuId());
                Integer saveSuccessId = webUserMenuService.saveUsermenu(webUsermenuEntity);
                if (saveSuccessId == 0) {
                    return 0;//新增栏目关联表失败
                }
            }
        }
        //更新数据范围关联表
        if (param.getId() > 0) {//只有编辑时才会执行删除
            Integer delUaSuccessId = webUserareaService.delUserareaByUserId(param.getId());
            //if(delUaSuccessId==0) return 0;//删除数据范围关联表失败
        }

        if (StringUtils.isNotBlank(param.getDataRangeStr())) {
            String[] dataRangeIds = param.getDataRangeStr().split(",");
            for (String areaId : dataRangeIds) {
                WebUserareaEntity webUserareaEntity = new WebUserareaEntity();
                webUserareaEntity.setUserid(entity.getId());
                webUserareaEntity.setAreaid(Integer.parseInt(areaId));
                Integer saveUaSuccessId = webUserareaService.saveUserarea(webUserareaEntity);
                if (saveUaSuccessId == 0) return 0;//新增数据范围关联表失败
            }
        }
        return 1;
    }

    @Override
    public List<WebMenuModel> searchMenusByPlatformId(Integer platformId) {

        WebPlatformEntity webPlatformEntity = webPlatformService.searchById(platformId);
        if (webPlatformEntity != null) {
            Integer rolesId = webPlatformEntity.getRolesid();
            if (rolesId != null && rolesId > 0) {
                List<WebRolesmenuRlatEntity> webRolesmenuRlatEntities = webRolesmenuRlatService.searchByRolesID(rolesId);
                if (webRolesmenuRlatEntities != null && webRolesmenuRlatEntities.size() > 0) {
                    //List<WebMenuEntity> webMenuEntities=new ArrayList<>();
                    List<WebMenuModel> webMenuModels = new ArrayList<>();
                    for (WebRolesmenuRlatEntity webRolesmenuRlatEntity : webRolesmenuRlatEntities) {
                        WebMenuEntity webMenuEntity = webMenuService.searchById(webRolesmenuRlatEntity.getMenuid());
                        WebMenuModel model = new WebMenuModel();
                        mapper.map(webMenuEntity, model);
                        webMenuModels.add(model);
                    }
                    return webMenuModels;
                }
            }
        }
        return null;
    }

    @Override
    public DataRangeModel searchDrByPlatformId(Integer platformId) {

        if (platformId != null && platformId > 0) {
            WebPlatformEntity webPlatformEntity = webPlatformService.searchById(platformId);
            if (webPlatformEntity != null) {
                DataRangeModel dataRangeModel = new DataRangeModel();
                if (webPlatformEntity.getType() != null && webPlatformEntity.getType() > 0) {
                    String parentName = "";
                    switch (webPlatformEntity.getType()) {
                        case 1:
                            parentName = webPlatformEntity.getProvince();
                            break;
                        case 2:
                            parentName = webPlatformEntity.getCity();
                            break;
                        case 3:
                        case 4:
                            parentName = webPlatformEntity.getArea();
                            break;
                        default:
                            break;
                    }
                    dataRangeModel.setParentName(parentName);
                }
                List<WebPlatformareaEntity> webPlatformareaEntities = web_platformareaService.searchByPlatformId(platformId);
                List<WebPlatformareaModel> models = new ArrayList<>();
                if (webPlatformareaEntities != null && webPlatformareaEntities.size() > 0) {
                    for (WebPlatformareaEntity webPlatformareaEntity : webPlatformareaEntities) {
                        WebPlatformareaModel model = new WebPlatformareaModel();
                        mapper.map(webPlatformareaEntity, model);
                        models.add(model);
                    }
                }
                dataRangeModel.setPaEntities(models);
                if (StringUtils.isBlank(dataRangeModel.getParentName())) {
                    return null;
                }
                return dataRangeModel;
            }
        }
        return null;
    }

    @Override
    public WebUserInfoViewModel searchUserInfoById(Integer id) {
        WebUserinfoEntity entity = queryById(id);
        if (entity == null) return null;
        WebUserInfoViewModel model = new WebUserInfoViewModel();
        mapper.map(entity, model);

        model.setPwd(EncryptionStrategy.decrypt(model.getPwd()));

        //获取该平台的菜单
        List<WebMenuModel> webMenuModels = searchMenusByPlatformId(entity.getPlatformid());
        //获取该用户的菜单
        if (webMenuModels != null && webMenuModels.size() > 0) {
            List<WebUsermenuEntity> webUsermenuEntities = webUserMenuService.searchByUserId(entity.getId());
            if (webUsermenuEntities != null && webUsermenuEntities.size() > 0) {
                for (WebUsermenuEntity webUsermenuEntity : webUsermenuEntities) {
                    for (WebMenuModel webMenuModel : webMenuModels) {
                        if (webUsermenuEntity.getMenuid() == webMenuModel.getId()) {
                            webMenuModel.setIsChecked(true);
                            if (webMenuModel.getIssys()) {
                                webMenuModel.setIsReadOnly(webUsermenuEntity.getIsreadonly());
                            }
                        }
                    }
                }
            }
        }
        model.setWebMenuModels(webMenuModels);

        //获取该平台的区域
        DataRangeModel dataRangeModel = searchDrByPlatformId(entity.getPlatformid());
        if (dataRangeModel != null && dataRangeModel.getPaEntities() != null && dataRangeModel.getPaEntities().size() > 0) {
            //获取该用户的区域
            List<WebUserareaEntity> webUserareaEntities = webUserareaService.searchUserareaByUserId(entity.getId());
            if (webUserareaEntities != null && webUserareaEntities.size() > 0) {
                for (WebUserareaEntity webUserareaEntity : webUserareaEntities) {
                    List<WebPlatformareaModel> webPlatformareaModels = dataRangeModel.getPaEntities();
                    for (WebPlatformareaModel webPlatformareaModel : webPlatformareaModels) {
                        if (webUserareaEntity.getAreaid().intValue() == webPlatformareaModel.getId().intValue()) {
                            webPlatformareaModel.setIsChecked(true);
                        }
                    }
                }
            }
        }
        model.setDataRangeModel(dataRangeModel);

        return model;
    }

    @Override
    public Boolean checkUserName(String userName) {

        List<WebUserinfoEntity> entities = queryAll();
        if (entities != null && entities.size() > 0) {
            for (WebUserinfoEntity entity : entities) {
                if (entity.getName().equals(userName.trim())) {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public Integer delUserInfoByIds(String ids, int userId) {

        if (StringUtils.isNotBlank(ids)) {
            String[] idStr = ids.split(",");
            WebUserinfoEntity entity = new WebUserinfoEntity();
            entity.setStatus(-1);
            entity.setUpdateoperid(userId);
            for (String id : idStr) {
                entity.setId(Integer.parseInt(id));
                entity.setUpdatedate(new Date());
                Integer successId = updateByNotNull(entity);
                if (successId == 0) return 0;//删除失败
            }
            return 1;
        }

        return 0;
    }

    @Override
    public Integer setStatusOfUserInfo(int id, int status, int userId) {
        WebUserinfoEntity entity = new WebUserinfoEntity();
        entity.setId(id);
        entity.setStatus(status);
        entity.setUpdateoperid(userId);
        entity.setUpdatedate(new Date());
        Integer successId = updateByNotNull(entity);
        if (successId == 0) return 0;//修改失败
        return 1;
    }

    @Override
    public PageResult<WebUserinfoEntity> searchUserInfo(SearchPage param) {

        PageHelper.startPage(param.getPage(), param.getPageSize());
        Mapper<WebUserinfoEntity> mapperTk = getMapper();
        Example example = new Example(WebUserinfoEntity.class);
        example.setOrderByClause("createdate DESC");
        Example.Criteria criteria = example.createCriteria();
        criteria.andNotEqualTo("status", -1);
        List<WebUserinfoEntity> entities = mapperTk.selectByExample(example);
        PageInfo<WebUserinfoEntity> pageInfo = new PageInfo<>(entities);
        if (entities != null && entities.size() > 0)
            return new PageResult<WebUserinfoEntity>(entities, param.getPage(), param.getPageSize(), (int) pageInfo.getTotal());
        return null;
    }

    @Override
    public List<WebDto> searchUserInfoByIds(String idStr) {

        if (StringUtils.isNotBlank(idStr)) {
            List<WebDto> list = new ArrayList<WebDto>();
            String[] ids = idStr.split(",");
            for (String id : ids) {
                WebDto webDto = new WebDto();
                WebUserinfoEntity entity = queryById(Integer.parseInt(id));
                mapper.map(entity, webDto);
                String createdateStr = "";
                String logindateStr = "";
                if (entity.getCreatedate() != null) {
                    createdateStr = getDate(entity.getCreatedate());
                }
                if (entity.getLogindate() != null) {
                    logindateStr = getDate(entity.getLogindate());
                }
                webDto.setCreatedatestr(createdateStr);
                webDto.setLogindatestr(logindateStr);
                list.add(webDto);
            }
            return list;
        }
        return null;
    }

    @Override
    public Map<String, String> getMapExcel(List<WebDto> webDtos) {

        Map<String, String> mapExcel = new HashMap<String, String>();
        mapExcel.put("title", "区域监控信息表");
        mapExcel.put("total", webDtos.size() + " 条");
        mapExcel.put("date", getDate(new Date()));
        return mapExcel;
    }

    @Override
    public Res editPassword(Integer userId, String newPwd) {
        WebUserinfoEntity entity = webUserDao.selectByPrimaryKey(userId);
        //加密
        entity.setPwd(EncryptionStrategy.encrypt(newPwd));
        int i = webUserDao.updateByPrimaryKey(entity);
        return Res.ok();
    }


    private static String getDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        return sdf.format(date);
    }


    @Override
    public boolean updateLoginInfo(WebUserUpdateLoginInfo updateLoginInfo) {
        Map<String, Object> map = new HashMap<>();
        map.put("LoginCount", updateLoginInfo.getLoginCount());
        map.put("LoginDate", updateLoginInfo.getLoginDate());
        map.put("IPAdress", updateLoginInfo.getIp());
        map.put("Brower", updateLoginInfo.getBrower());
        return webUserDao.updateByMap(map, updateLoginInfo.getId()) > 0;

    }




}
